import { DICT_TYPE, getDictOptions } from "@/utils/dict";
import * as DeptApi from "@/api/system/dept";
// import ProcessExpressionDialog from './ProcessExpressionDialog.vue'
// import { ProcessExpressionVO } from '@/api/bpm/processExpression'
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { getSimpleRoleList } from "@/api/system/role";
import { getSimplePostList } from "@/api/system/post";
import { useEffect } from "react";
import { handleTree } from "@/utils/tree";
import { getSimpleUserList } from "@/api/system/user";
import { getUserGroupSimpleList } from "@/api/bpm/userGroup";
import { isArray } from "@/utils/is";

let bpmnElement: any = null;
let deptTreeOptions: any[] = [];
export default function UserTask(props: any) {
	const bpmnInstances = () => (window as any)?.bpmnInstances;
	const schemas: FormSchema[] = [
		{
			label: "规则类型",
			field: "candidateStrategy",
			component: "Select",
			componentProps: {
				options: getDictOptions(DICT_TYPE.BPM_TASK_CANDIDATE_STRATEGY),
				onChange: () => changeCandidateStrategy()
			}
		},
		{
			label: "指定角色",
			field: "candidateParam1",
			component: "ApiSelect",
			componentProps: {
				api: getSimpleRoleList,
				mode: "multiple",
				labelField: "name",
				valueField: "id",
				onChange: () => updateElementTask()
			},
			ifShow: ({ values }) => values.candidateStrategy == "10"
		},
		{
			label: "指定部门",
			field: "candidateParam2",
			component: "TreeSelect",
			componentProps: {
				treeData: [],
				fieldNames: {
					value: "id",
					label: "name"
				},
				treeCheckable: true,
				onChange: () => updateElementTask()
			},
			ifShow: ({ values }) => values.candidateStrategy == "20" || values.candidateStrategy == "21"
		},
		{
			label: "指定岗位",
			field: "candidateParam3",
			component: "ApiSelect",
			componentProps: {
				api: getSimplePostList,
				mode: "multiple",
				labelField: "name",
				valueField: "id",
				onChange: () => updateElementTask()
			},
			ifShow: ({ values }) => values.candidateStrategy == "22"
		},
		{
			label: "指定用户",
			field: "candidateParam4",
			component: "ApiSelect",
			componentProps: {
				api: getSimpleUserList,
				mode: "multiple",
				labelField: "nickname",
				valueField: "id",
				onChange: () => updateElementTask()
			},
			ifShow: ({ values }) => values.candidateStrategy == "30"
		},
		{
			label: "指定用户组",
			field: "candidateParam5",
			component: "ApiSelect",
			componentProps: {
				api: getUserGroupSimpleList,
				mode: "multiple",
				labelField: "name",
				valueField: "id",
				onChange: () => updateElementTask()
			},
			ifShow: ({ values }) => values.candidateStrategy == "40"
		},
		{
			label: "流程表达式",
			field: "candidateParam6",
			component: "InputTextArea",
			componentProps: {
				onChange: () => updateElementTask()
			},
			ifShow: ({ values }) => values.candidateStrategy == "60"
		}
	];
	const fields = schemas.filter(ele => ele.field.includes("candidateParam")).map(item => item.field);
	const [registerForm, { setFieldsValue, getFieldsValue, resetFields, updateSchema }] = useForm({
		schemas,
		showActionButtonGroup: false,
		labelWidth: 120,
		baseColProps: { span: 24 }
	});

	/** Function */

	const resetTaskForm = async () => {
		const businessObject = bpmnElement.businessObject;
		if (!businessObject) {
			return;
		}
		let candidateParam =
			businessObject.candidateParam && businessObject.candidateParam.length > 0
				? businessObject.candidateStrategy === 60
					? [businessObject.candidateParam]
					: businessObject.candidateParam.split(",").map(item => +item)
				: [];
		let formValues: Recordable = {
			candidateStrategy: businessObject.candidateStrategy != undefined ? parseInt(businessObject.candidateStrategy) : undefined
		};
		schemas.forEach(ele => {
			if (ele.field.includes("candidateParam")) formValues[ele.field] = candidateParam;
		});
		// resetFields();
		console.log("UserTask-businessObject", businessObject, formValues);
		setFieldsValue(formValues);
	};

	// 更新 candidateStrategy 字段时，需要清空 candidateParam，并触发 bpmn 图更新
	const changeCandidateStrategy = () => {
		// 用户输入才能触发清空
		resetFields(fields);
		updateElementTask();
	};

	/** 选中某个 options 时候，更新 bpmn 图  */
	const updateElementTask = async () => {
		const values = await getFieldsValue();
		let valueField: string = Object.keys(values).find(ele => ele.includes("candidateParam"))!;
		console.log("UserTask-updateElementTask", values, values[valueField]);
		bpmnInstances().modeling.updateProperties(bpmnElement, {
			candidateStrategy: values.candidateStrategy,
			candidateParam:
				values[valueField] && isArray(values[valueField]) ? values[valueField].join(",") : values?.[valueField] ?? ""
		});
	};

	// 打开监听器弹窗
	// const processExpressionDialogRef = ref();
	// const openProcessExpressionDialog = async () => {
	// 	processExpressionDialogRef.value.open();
	// };
	// const selectProcessExpression = (expression: ProcessExpressionVO) => {
	// 	userTaskForm.value.candidateParam = [expression.expression];
	// 	updateElementTask();
	// };

	/** Request */

	// 获得部门列表
	const getOptions = async () => {
		const deptOptions = await DeptApi.getSimpleDeptList();
		deptTreeOptions = handleTree(deptOptions, "id");
		updateSchema({
			field: "candidateParam2",
			componentProps: {
				treeData: deptTreeOptions
			}
		});
	};

	/** Effect */

	useEffect(() => {
		bpmnElement = bpmnInstances().bpmnElement;
		resetTaskForm();
	}, [props.id]);

	useEffect(() => {
		getOptions();
		return () => {
			console.log("UserTask销毁");
			bpmnElement = null;
		};
	}, []);

	return <BasicForm register={registerForm} />;
}
